/*
 * Copyright (c) 2023-2023 elsfs Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.elsfs.cloud.common.configuration;

import lombok.extern.slf4j.Slf4j;
import org.elsfs.cloud.common.properties.ElsfsSecurityProperties;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.AutoConfigureOrder;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

/**
 * 跨域请求相关配置
 *
 * @author zeng
 */
@AutoConfiguration
@ConditionalOnClass(ElsfsSecurityProperties.class)
@EnableConfigurationProperties(ElsfsSecurityProperties.class)
@AutoConfigureOrder(Integer.MIN_VALUE)
@ConditionalOnProperty(prefix = "elsfs.security.cors", value = "enabled", havingValue = "true")
@Slf4j
public class AutoCorsConfiguration {

  /**
   * 配置跨域请求
   *
   * @param elsfsSecurityProperties p
   * @return f
   */
  @Bean("corsFilter")
  @ConditionalOnMissingBean
  public CorsFilter corsFilter(ElsfsSecurityProperties elsfsSecurityProperties) {
    LOGGER.info("Configure the cors filter .....");
    ElsfsSecurityProperties.Cors cors = elsfsSecurityProperties.getCors();
    CorsConfiguration config = new CorsConfiguration();
    config.setAllowedOrigins(cors.getOrigins());
    config.setAllowedOriginPatterns(cors.getAllowedOriginPatterns());
    config.setAllowedHeaders(cors.getAllowedHeaders());
    config.setMaxAge(18000L);
    config.setAllowedMethods(cors.getAllowedMethods());
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", config);
    return new CorsFilter(source);
  }
}
